package cn.gyouzhe.service.impl;

import cn.gyouzhe.entity.Good;
import cn.gyouzhe.mapper.GoodMapper;
import cn.gyouzhe.mapper.vo.ColumnCountVo;
import cn.gyouzhe.service.IGoodService;
import cn.gyouzhe.vo.GoodVo;
import cn.gyouzhe.vo.PageResult;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商品service
 *
 * @author wangchuan
 * @datetime 2018/3/3 16:12
 */
@Service
@Transactional(readOnly = true)
public class GoodService implements IGoodService {
    @Autowired
    private GoodMapper goodMapper;

    /**
     * 查询商品
     * @param goodId 商品ID
     * @return 商品实体
     */
    @Override
    public Good selectGood(String goodId) {
        return goodMapper.selectGood(goodId);
    }

    /**
     * 查询商品栏目总数
     * @return 商品栏目总数
     */
    @Override
    public Map<Integer, Integer> selectColumnGoodCount() {
        List<ColumnCountVo> columnCountVos = goodMapper.selectColumnGoodCount();
        Map<Integer, Integer> columnCountMap = columnCountVos.stream().collect(Collectors.toMap(ColumnCountVo::getCid, ColumnCountVo::getCount));
        return columnCountMap;
    }

    /**
     * 分页查询商品列表
     * @param pagekey 页码类型
     * @param cid 商品栏目
     * @param pageNo  页码
     * @param pageSize  每页显示大小
     * @param type  商品类型
     * @param sort 排序 p价格 s销量 n最新
     * @return 商品列表
     */
    @Override
    public PageResult<GoodVo> selectGoodInfo(String pagekey, int cid, int pageNo, int pageSize, int type, String sort) {
        Page<GoodVo> page = PageHelper.startPage(pageNo, pageSize, true);
        List<GoodVo> goods = goodMapper.selectGoodInfo(pagekey, cid, type, sort);
        return PageResult.of(pageNo, pageSize, (int) page.getTotal(), goods);
    }

    /**
     * 保存商品
     * @param good 商品实体
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
    @Override
    public void saveGood(Good good) {
        goodMapper.saveGood(good);
    }

    /**
     * 更新商品
     * @param good 商品信息
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
    @Override
    public void updateGood(Good good) {
        goodMapper.updateGood(good);
    }

    /**
     * 过期商品
     * @param goodId 商品ID
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
    public void expireGood(String goodId){
        goodMapper.expireGood(goodId);
    }
}
